package application;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Handler;
import android.widget.Toast;


import java.util.ArrayList;
import java.util.List;

/**
 * @author 李志培
 *         <p/>
 *         作者信息：嘉应学院1303班
 *         <p/>
 *         创建日期：2016-4-23下午3:59
 *         <p/>
 *         类描述：自定义application
 *         <p/>
 *         修改历史：
 */
public class MyApplication extends Application {
    private static MyApplication mApplication;
    private static Handler mHandler;
    private static List<Activity> mActivityList;

    @Override
    public void onCreate() {
        super.onCreate();
        mApplication = this;
        mHandler = new Handler();
        mActivityList = new ArrayList<Activity>();
    }

    public static boolean isActivityListEmpty() {
        if (mActivityList.size() <= 0) {
            return true;
        }
        return false;
    }

    public static int getActivityCount() {
        return mActivityList.size();
    }

    public synchronized static void addActivity(Activity activity) {
        mActivityList.add(activity);
    }

    public synchronized static void removeActivity(Activity activity) {
        mActivityList.remove(activity);
    }

    /**
     * 异步执行任务
     * @param runnable
     */
    public static void RunAsync(Runnable runnable){

        new MyAsyncTask(runnable).execute();
    }


    /**
     * 程序销毁
     */
    @Override
    public void onTerminate() {
        super.onTerminate();
        DestroyApplication();
    }


    /**
     * 销毁应用
     */
    public synchronized static void DestroyApplication() {
        for (Activity activity : mActivityList) {
            activity.finish();
        }
        mActivityList.clear();
    }

    public static Context getContext() {
        return mApplication;
    }

    public static Activity getLastActivity(){
        return mActivityList.get(getActivityCount()-1);
    }

    /**
     * 主线程执行任务
     * @param runnable
     */
    public static void RunOnMainThread(Runnable runnable) {
        mHandler.post(runnable);
    }
    /**
     * 弹出Toast
     */
    public static void ShowToast(final String message, final int duration) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(mApplication, message, duration).show();
            }
        });
    }

}

